﻿using Activity.Data;
using Activity.Helper;
using Activity.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Activity.API
{
    /// <summary>
    /// 门店巡检-工单系统应用接口
    /// </summary>
    public class WorkOrderHandler
    {
        /// <summary>
        /// 获取类别信息
        /// </summary>
        /// <returns></returns>
        public IList<DictionarylVO> GetWdTypeList()
        {
            List<DictionarylVO> list = new List<DictionarylVO>();
            using (ActivityEntities activityEntities = new ActivityEntities())
            {
                var queryable = activityEntities.t_inspection_setting.Where(c => c.isRemove == false && c.ins_childCode == "0").Select(
                    d => new DictionarylVO
                    {
                        Code = d.ins_parentCode,
                        Name = d.ins_parentShortName
                    }).OrderBy(d => d.Code).ToList();
                list = queryable.ToList();
            }
            return list;
        }
        /// <summary>
        /// 获取字典信息
        /// </summary>
        /// <param name="groupName">类别组</param>
        /// <returns></returns>
        public IList<DictionarylVO> GetDicTionaryList(string groupName)
        {
            List<DictionarylVO> list = new List<DictionarylVO>();
            using (ActivityEntities activityEntities = new ActivityEntities())
            {
                var queryable = activityEntities.km_dictionary.Where(c => c.GroupName == groupName).Select(
                    d => new DictionarylVO
                    {
                        Code = d.Code,
                        Name = d.Name,
                        Value = d.Value
                    }).Distinct().OrderBy(d => d.Code);
                list = queryable.ToList();
            }
            return list;
        }
        /// <summary>
        /// 查询扣分项
        /// </summary>
        /// <returns></returns>
        public IList<WordOrderVO.InfoAll> GetWordOrderVO(string w_code, DateTime? startDate, DateTime? endDate, string parentCode, int? w_type, int? tid_id, int? userID, int customUserType = 0)
        {
            IList<WordOrderVO.InfoAll> list = new List<WordOrderVO.InfoAll>();
            using (ActivityEntities activityEntities = new ActivityEntities())
            {
                var query = (from a in activityEntities.t_ins_workorderMaster
                             join b in activityEntities.t_inspection_finishDetail on a.tid_id equals b.tid_id
                             join c in activityEntities.t_inspection_finishMaster on b.tif_id equals c.tif_id
                             join d in activityEntities.t_inspection_setting on b.ins_id equals d.ins_id
                             where b.tid_points > 0 && c.isRemove == false
                             select new { b.tid_id, a.w_code, a.createDate, d.ins_checkContext, d.ins_parentCode, c.tif_shopCode, ShopName = c.tif_shopName, d.ins_parentName, c.tif_checkDate, CreateBy = a.createBy, a.w_id, a.w_type, a.creator });
                if (!string.IsNullOrEmpty(w_code))
                {
                    query = query.Where(c => c.w_code == w_code);
                }
                if (tid_id.HasValue && tid_id > 0)
                {
                    query = query.Where(c => c.tid_id == tid_id);
                }
                if (startDate.HasValue)
                {
                    query = query.Where(c => c.createDate >= DbFunctions.TruncateTime(startDate));
                }
                if (endDate.HasValue)
                {
                    query = query.Where(c => c.createDate <= DbFunctions.TruncateTime(endDate));
                }
                if (!string.IsNullOrEmpty(parentCode) && !parentCode.Equals("全部"))
                {
                    query = query.Where(c => c.ins_parentCode == parentCode);
                }
                if (w_type.HasValue && w_type > 0)
                {
                    query = query.Where(c => c.w_type == w_type);
                }
                if (customUserType == 1)
                {
                    var shopCodes = activityEntities.V_UserShopDataRights.Where(c => c.userid == userID).Select(c => c.shopcode).Distinct().ToArray();
                    query = query.Where(c => shopCodes.Any(shopCode => shopCode == c.tif_shopCode));
                }
                else
                {
                    if (userID.HasValue)
                    {
                        query = query.Where(c => c.creator == userID);
                    }
                }
                query.ToList().ForEach(a => list.Add(new WordOrderVO.InfoAll { tid_id = a.tid_id, w_code = a.w_code.ToString(), CreateBy = a.CreateBy, CreateDate = a.createDate, ins_checkContext = a.ins_checkContext, ins_parentCode = a.ins_parentCode, ins_parentName = a.ins_parentName, ShopCode = a.tif_shopCode, ShopName = a.ShopName, tif_checkDate = a.tif_checkDate, w_id = a.w_id, w_type = a.w_type }));
            }
            return list;
        }
        /// <summary>
        /// 获取店铺信息
        /// </summary>
        /// <param name="shopNames">店铺名称</param>
        /// <returns></returns>
        public IList<VShopModel.ShopModel> GetShopList(string shopNames, int userId)
        {
            List<VShopModel.ShopModel> list = new List<VShopModel.ShopModel>();
            using (ActivityEntities activityEntities = new ActivityEntities())
            {
                var query = activityEntities.t_inspection_finishMaster.Where(c => c.tif_progress == 1 && c.isRemove == false).Select(
                    d => new VShopModel.ShopModel
                    {
                        ShopCode = d.tif_shopCode,
                        ShopName = d.tif_shopName
                    }).Distinct().OrderBy(d => d.ShopCode).AsQueryable();

                if (!string.IsNullOrEmpty(shopNames))
                {
                    query = query.Where(c => c.ShopName.Contains(shopNames));
                }
                if (userId > 0)
                {
                    var shopCodes = activityEntities.V_UserShopDataRights.Where(c => c.userid == userId).Select(c => c.shopcode).Distinct().ToArray();
                    query = query.Where(c => shopCodes.Any(d => d == c.ShopCode));
                }
                list = query.ToList();
                foreach (var item in list)
                {
                    item.tif_checkDate = activityEntities.t_inspection_finishMaster.Where(d => d.tif_shopCode == item.ShopCode && d.tif_progress == 1).Max(d => d.tif_checkDate);
                }
            }
            return list;
        }
        /// <summary>
        /// 获取店铺问题列表
        /// </summary>
        /// <param name="shopCode">店铺编码</param>
        /// <param name="checkDate">巡检时间</param>
        /// <returns></returns>
        public IList<WordOrderVO.OrderTable> GetShopProblemList(string shopCode, DateTime? checkDate)
        {
            IList<WordOrderVO.OrderTable> list = new List<WordOrderVO.OrderTable>();
            using (ActivityEntities activityEntities = new ActivityEntities())
            {
                var query = (from a in activityEntities.t_inspection_finishDetail
                             join b in activityEntities.t_inspection_finishMaster on a.tif_id equals b.tif_id
                             join c in activityEntities.t_inspection_setting on a.ins_id equals c.ins_id
                             where a.tid_points > 0 && b.tif_progress == 1 && b.isRemove == false && !activityEntities.t_ins_workorderMaster.Any(dc => dc.tid_id == a.tid_id)
                             select new WordOrderVO.OrderTable { tid_id = a.tid_id, ShopCode = b.tif_shopCode, ShopName = b.tif_shopName, ins_checkContext = c.ins_checkContext, tif_checkDate = b.tif_checkDate, tid_remarks = a.tid_remarks, tid_points = a.tid_points });
                if (!string.IsNullOrEmpty(shopCode))
                {
                    query = query.Where(c => c.ShopCode == shopCode);
                }
                if (checkDate.HasValue)
                {
                    query = query.Where(c => c.tif_checkDate >= DbFunctions.TruncateTime(checkDate));
                }
                list = query.ToList();
            }
            //放图片
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.TidImgList = GetInsImg(item.tid_id, 1);
                }
            }
            return list;
        }
        /// <summary>
        /// 获取扣分明细+沟通明细
        /// </summary>
        /// <param name="tid_id"></param>
        /// <returns></returns>
        public WordOrderVO.DetailFrom GetDetailByTidId(int? tid_id)
        {
            WordOrderVO.DetailFrom detailFrom = new WordOrderVO.DetailFrom();
            if (tid_id.HasValue && tid_id.Value > 0)
            {
                using (ActivityEntities activityEntities = new ActivityEntities())
                {
                    var a = activityEntities.t_inspection_finishDetail.FirstOrDefault(t => t.tid_id == tid_id);
                    if (a != null)
                    {
                        var b = activityEntities.t_inspection_finishMaster.FirstOrDefault(t => t.tif_id == a.tif_id);
                        var c = activityEntities.t_inspection_setting.FirstOrDefault(t => t.ins_id == a.ins_id);
                        detailFrom.tid_id = a.tid_id;
                        detailFrom.tid_points = a.tid_points;
                        detailFrom.tid_remarks = a.tid_remarks;
                        detailFrom.ShopCode = b.tif_shopCode;
                        detailFrom.ins_checkContext = c.ins_checkContext;
                        detailFrom.ins_parentCode = c.ins_parentCode;
                        detailFrom.ins_parentName = c.ins_parentName;
                        detailFrom.ShopName = b.tif_shopName;
                        detailFrom.tif_checkDate = b.tif_checkDate;
                        var d = activityEntities.t_ins_workorderMaster.FirstOrDefault(t => t.tid_id == tid_id);
                        if (d != null)
                        {
                            detailFrom.w_code = d.w_code.ToString();
                            detailFrom.w_id = d.w_id;
                            detailFrom.w_type = d.w_type;
                            detailFrom.creator = d.creator;
                            detailFrom.W_Details = activityEntities.t_ins_workorderDetail.Where(t => t.w_id == d.w_id).Select(s => new W_Detail { wd_id = s.wd_id, wd_checktype = s.wd_checktype, wd_context = s.wd_context, wd_submitter = s.wd_submitter, wd_submittime = s.wd_submittime, wd_type = s.wd_type }).ToList();
                        }
                    }
                }
                detailFrom.TidImgList = GetInsImg(tid_id, 1);
                if (detailFrom.W_Details != null && detailFrom.W_Details.Count > 0)
                {
                    foreach (var item in detailFrom.W_Details)
                    {
                        item.wd_ImgList = GetInsImg(item.wd_id, 3);
                    }
                }
            }
            return detailFrom;
        }
        /// <summary>
        /// 查看工单明细
        /// </summary>
        /// <param name="wId"></param>
        /// <returns></returns>
        public WordOrderVO.DetailFrom GetDetailByWId(int? wId)
        {
            WordOrderVO.DetailFrom detailFrom = new WordOrderVO.DetailFrom();
            if (wId.HasValue && wId.Value > 0)
            {
                using (ActivityEntities activityEntities = new ActivityEntities())
                {
                    var d = activityEntities.t_ins_workorderMaster.FirstOrDefault(t => t.w_id == wId);
                    if (d != null)
                    {
                        if (d != null)
                        {
                            detailFrom.w_code = d.w_code.ToString();
                            detailFrom.w_id = d.w_id;
                            detailFrom.W_Details = activityEntities.t_ins_workorderDetail.Where(t => t.w_id == d.w_id).Select(s => new W_Detail { wd_id = s.wd_id, wd_checktype = s.wd_checktype, wd_context = s.wd_context, wd_submitter = s.wd_submitter, wd_submittime = s.wd_submittime, wd_type = s.wd_type }).ToList();
                        }
                        var a = activityEntities.t_inspection_finishDetail.FirstOrDefault(t => t.tid_id == d.tid_id);
                        var b = activityEntities.t_inspection_finishMaster.FirstOrDefault(t => t.tif_id == a.tif_id);
                        var c = activityEntities.t_inspection_setting.FirstOrDefault(t => t.ins_id == a.ins_id);
                        detailFrom.w_type = d.w_type;
                        detailFrom.tid_id = a.tid_id;
                        detailFrom.creator = d.creator;
                        detailFrom.tid_points = a.tid_points;
                        detailFrom.tid_remarks = a.tid_remarks;
                        detailFrom.ShopName = b.tif_shopCode;
                        detailFrom.ins_checkContext = c.ins_checkContext;
                        detailFrom.ins_parentCode = c.ins_parentCode;
                        detailFrom.ins_parentName = c.ins_parentName;
                        detailFrom.ShopCode = b.tif_shopCode;
                        detailFrom.ShopName = b.tif_shopName;
                        detailFrom.tif_checkDate = b.tif_checkDate;
                    }
                }
                detailFrom.TidImgList = GetInsImg(detailFrom.tid_id, 1);
                if (detailFrom.W_Details != null && detailFrom.W_Details.Count > 0)
                {
                    foreach (var item in detailFrom.W_Details)
                    {
                        item.wd_ImgList = GetInsImg(item.wd_id, 3);
                    }
                }
            }
            return detailFrom;
        }
        /// <summary>
        /// 保存工单数据
        /// </summary>
        /// <param name="savaModel"></param>
        /// <returns></returns>
        public WordOrderVO.SavaModel SavaModel(WordOrderVO.SavaModel savaModel, out string msg, out bool result)
        {
            WordOrderVO.SavaModel model = null;
            result = false;
            msg = "";
            using (ActivityEntities activityEntities = new ActivityEntities())
            {
                if (savaModel != null)
                {
                    var wmModel = activityEntities.t_ins_workorderMaster.FirstOrDefault(c => c.w_id == savaModel.w_id);
                    if (wmModel == null)
                    {
                        //创建主单
                        string wCode = "QW-" + DateTime.Now.ToString("yyyyMMdd") + "-";
                        var maxModel = activityEntities.t_ins_workorderMaster.OrderByDescending(c => c.createDate).FirstOrDefault();
                        var index = 0;
                        if (maxModel != null)
                        {
                            int.TryParse(maxModel.w_code.Substring(wCode.Length), out index);
                            index++;
                        }
                        string codeIndex = (10000 + index).ToString().Substring(1);
                        wCode += codeIndex;
                        var d_model = savaModel.w_Detail;
                        wmModel = new t_ins_workorderMaster { w_code = wCode, creator = savaModel.creator.Value, createBy = d_model.wd_submitter, createDate = DateTime.Now, tid_id = savaModel.tid_id.Value, w_type = 1 };
                        activityEntities.t_ins_workorderMaster.Add(wmModel);
                        activityEntities.SaveChanges();

                        t_ins_workorderDetail wdModel = new t_ins_workorderDetail { w_id = wmModel.w_id, wd_submitter = d_model.wd_submitter, wd_context = d_model.wd_context, wd_type = 1, wd_submittime = DateTime.Now };
                        activityEntities.t_ins_workorderDetail.Add(wdModel);
                        activityEntities.SaveChanges();

                        savaModel.w_code = wCode;
                        savaModel.w_id = wmModel.w_id;
                        savaModel.w_Detail.wd_checktype = wdModel.wd_checktype;
                        savaModel.w_Detail.wd_id = wdModel.wd_id;
                        savaModel.w_Detail.wd_type = wdModel.wd_type;
                        savaModel.w_Detail.wd_submittime = wdModel.wd_submittime;

                        var imgList = savaModel.w_Detail.wd_ImgList;
                        if (imgList != null && imgList.Count > 0)
                        {
                            foreach (var item in imgList)
                            {
                                t_inspection_img imgItem = new t_inspection_img { Img_ID = new Guid(item.ImageId), img_type = 3, tid_id = wdModel.wd_id };
                                activityEntities.t_inspection_img.Add(imgItem);
                                activityEntities.SaveChanges();
                            }
                        }
                        model = savaModel;
                        result = true;
                        msg = "";
                    }
                    else
                    {
                        var list = activityEntities.t_ins_workorderDetail.Where(c => c.wd_context == savaModel.w_Detail.wd_context && c.w_id == savaModel.w_id).ToList();
                        if (list != null && list.Count > 0)
                        {
                            result = false;
                            msg = "不能重复提交消息！";
                            return savaModel;
                        }
                        var d_model = savaModel.w_Detail;

                        //重新申诉
                        if (savaModel.resetModel.HasValue && savaModel.resetModel == 1)
                        {
                            wmModel.w_type = 1;
                        }
                        else
                        {
                            if (d_model.wd_checktype.HasValue)
                            {
                                wmModel.w_type = 2;
                                if (d_model.wd_checktype.Value)
                                {
                                    wmModel.w_type = 3;
                                }
                            }
                        }
                        activityEntities.Entry(wmModel).State = EntityState.Modified;
                        activityEntities.SaveChanges();
                        t_ins_workorderDetail wdModel = new t_ins_workorderDetail { w_id = wmModel.w_id, wd_submitter = d_model.wd_submitter, wd_context = d_model.wd_context, wd_type = d_model.wd_type.Value, wd_checktype = d_model.wd_checktype, wd_submittime = DateTime.Now };
                        activityEntities.t_ins_workorderDetail.Add(wdModel);
                        activityEntities.SaveChanges();
                        savaModel.w_Detail.wd_checktype = wdModel.wd_checktype;
                        savaModel.w_Detail.wd_id = wdModel.wd_id;
                        savaModel.w_Detail.wd_type = wdModel.wd_type;
                        savaModel.w_Detail.wd_submittime = wdModel.wd_submittime;
                        model = savaModel;
                        var imgList = savaModel.w_Detail.wd_ImgList;
                        if (imgList != null && imgList.Count > 0)
                        {
                            foreach (var item in imgList)
                            {
                                t_inspection_img imgItem = new t_inspection_img { Img_ID = new Guid(item.ImageId), img_type = 3, tid_id = wdModel.wd_id };
                                activityEntities.t_inspection_img.Add(imgItem);
                                activityEntities.SaveChanges();
                            }
                        }
                    }
                    result = true;
                    msg = "";
                }
            }
            return model;
        }
        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="tf_id"></param>
        /// <returns></returns>
        public IList<KmImgVO> GetInsImg(int? tid_id, int? img_type)
        {
            IList<KmImgVO> imgs = new List<KmImgVO>();
            if (tid_id > 0)
            {
                using (ActivityEntities activityEntities = new ActivityEntities())
                {
                    var items = activityEntities.t_inspection_img.Where(c => c.tid_id == tid_id && c.img_type == img_type).Join(activityEntities.kmImages, s => s.Img_ID, a => a.ID, (s, a) => new { ImageId = a.ID, tf_id = s.ID, a.Url, a.BucketName }).Take(3).ToList();
                    foreach (var item in items)
                    {
                        string imgId = item.ImageId.ToString();
                        imgs.Add(new KmImgVO { ImageId = imgId, tf_id = item.tf_id, Url = ImageHelper.GetOssUrl(item.BucketName, item.Url) });
                    }
                }
            }
            return imgs;
        }
        /// <summary>
        /// 删除工单项
        /// </summary>
        /// <param name="wId"></param>
        /// <returns></returns>
        public bool DelectByWId(int? wId, out string msg)
        {
            bool result = false;
            msg = string.Empty;
            if (wId.HasValue && wId > 0)
            {
                using (ActivityEntities activityEntities = new ActivityEntities())
                {
                    var wModel = activityEntities.t_ins_workorderMaster.FirstOrDefault(c => c.w_id == wId && c.w_type == 1);
                    if (wModel != null)
                    {
                        var canList = activityEntities.t_ins_workorderDetail.Where(c => c.wd_type == 2 && c.w_id == wId).ToList();
                        if (canList != null && canList.Count > 0)
                        {
                            result = false;
                            msg = "已有审批，不能删除！";
                        }
                        else
                        {
                            activityEntities.t_ins_workorderMaster.Remove(wModel);
                            var d_list = activityEntities.t_ins_workorderDetail.Where(c => c.w_id == wId).ToList();
                            if (d_list != null && d_list.Count > 0)
                            {
                                activityEntities.t_ins_workorderDetail.RemoveRange(d_list);
                            }
                            activityEntities.SaveChanges();
                            result = true;
                        }
                    }
                    else
                    {
                        result = false;
                        msg = "找不到工单，或者工单状态不在审批中！";
                    }
                }
            }
            else
            {
                result = false;
                msg = "找不到工单！";
            }
            return result;
        }
    }
    /// <summary>
    /// 字典--服务前端Model
    /// </summary>
    [Serializable]
    public class DictionarylVO
    {
        public string Code { get; set; }
        public string Name { get; set; }
        public int? Value { get; set; }
    }
    /// <summary>
    /// 工单系统主单--服务前端Model
    /// </summary>
    [Serializable]
    public class WordOrderVO
    {
        public class OrderBase
        {
            /// <summary>
            /// 主键
            /// </summary>
            public int? w_id { get; set; }
            /// <summary>
            /// 编码
            /// </summary>
            public string w_code { get; set; }
            /// <summary>
            /// 问题ID
            /// </summary>
            public int? tid_id { get; set; }
            /// <summary>
            /// 工单状态
            /// </summary>
            public int? w_type { get; set; }
            /// <summary>
            /// 店铺编码
            /// </summary>
            public string ShopCode { get; set; }
            /// <summary>
            /// 店铺名称
            /// </summary>
            public string ShopName { get; set; }
            /// <summary>
            /// 登陆者ID
            /// </summary>
            public int? creator { get; set; }
        }

        /// <summary>
        /// 查询简单信息用于表格
        /// </summary>
        public class OrderTable : OrderBase
        {
            /// <summary>
            /// 巡检时间
            /// </summary>
            public DateTime? tif_checkDate { get; set; }
            /// <summary>
            /// 问题内容
            /// </summary>
            public string ins_checkContext { get; set; }
            /// <summary>
            /// 扣分分数
            /// </summary>
            public decimal? tid_points { get; set; }
            /// <summary>
            /// 扣分描述
            /// </summary>
            public string tid_remarks { get; set; }
            /// <summary>
            /// 图片
            /// </summary>
            public IList<KmImgVO> TidImgList { get; set; }
        }

        public class DetailFrom : OrderTable
        {
            /// <summary>
            /// 类别编码
            /// </summary>
            public string ins_parentCode { get; set; }
            /// <summary>
            /// 类别名称
            /// </summary>
            public string ins_parentName { get; set; }
            /// <summary>
            /// 沟通明细
            /// </summary>
            public IList<W_Detail> W_Details { get; set; }
        }

        /// <summary>
        /// 用于审核
        /// </summary>
        public class CheckTable : OrderBase
        {
            /// <summary>
            /// 提交人
            /// </summary>
            public string wd_submitter { get; set; }
            /// <summary>
            /// 提交时间
            /// </summary>
            public DateTime? createDate { get; set; }
            /// <summary>
            /// 工单状态
            /// </summary>
            public int? w_type { get; set; }
            /// <summary>
            /// 沟通内容
            /// </summary>
            public string wd_context { get; set; }
        }

        public class InfoAll : DetailFrom
        {
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreateBy { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? CreateDate { get; set; }


        }
        /// <summary>
        /// 保存模型
        /// </summary>
        public class SavaModel : OrderBase
        {
            public int? resetModel { get; set; }
            /// <summary>
            /// 明细
            /// </summary>
            public W_Detail w_Detail { get; set; }
        }
    }
    /// <summary>
    /// 工单系统明细 -- 服务前端Model
    /// </summary>
    [Serializable]
    public class W_Detail
    {
        /// <summary>
        /// 主健
        /// </summary>
        public int? wd_id { get; set; }
        /// <summary>
        /// 提交人
        /// </summary>
        public string wd_submitter { get; set; }
        /// <summary>
        /// 沟通时间
        /// </summary>
        public DateTime? wd_submittime { get; set; }
        /// <summary>
        /// 沟通内容
        /// </summary>
        public string wd_context { get; set; }
        /// <summary>
        /// 对象类型
        /// </summary>
        public int? wd_type { get; set; }
        /// <summary>
        /// 审批意见
        /// </summary>
        public bool? wd_checktype { get; set; }
        /// <summary>
        /// 图片
        /// </summary>
        public IList<KmImgVO> wd_ImgList { get; set; }
    }
}
